package channel

import (
	"github.com/flaravel/quanlaolao/pkg/logger"
	"github.com/flaravel/quanlaolao/pkg/model"
	"github.com/flaravel/quanlaolao/pkg/pagination"
	"github.com/flaravel/quanlaolao/pkg/route"
	"github.com/flaravel/quanlaolao/pkg/types"
	"net/http"
)


func GetList() ([]Channel, error) {
	var channel []Channel
	if err := model.DB.Order("sort DESC").Find(&channel).Error; err != nil {
		return channel, err
	}
	return channel, nil
}

func GetAll(r *http.Request, perPage int) ([]Channel, pagination.ViewData, error) {

	db := model.DB.Model(&Channel{}).Order("created_at desc")
	_pager := pagination.New(r,  db, route.Name2URL("channel.index"), perPage)

	viewData := _pager.Paging()

	var channel []Channel
	_ = _pager.Results(&channel)

	return channel, viewData, nil
}

func Get(idstr string) (Channel, error) {
	var channel Channel
	id := types.StringToInt(idstr)
	if err := model.DB.First(&channel, id).Error; err != nil {
		return channel, err
	}

	return channel, nil
}

func (channel *Channel) Delete() (rowsAffected int64, err error) {
	result := model.DB.Delete(&channel)
	if err = result.Error; err != nil {
		logger.LogError(err)
		return 0, err
	}
	return result.RowsAffected, nil
}

func (channel *Channel) Update() (rowsAffected int64, err error) {
	result := model.DB.Save(&channel)
	if err = result.Error; err != nil {
		logger.LogError(err)
		return 0, err
	}
	return result.RowsAffected, nil
}

func (channel *Channel) Create() (err error) {
	if err = model.DB.Create(&channel).Error; err != nil {
		logger.LogError(err)
		return err
	}

	return nil
}